/**
 * ice v1.1.2
 * MIT License By www.iceui.net
 * 作者：ICE
 * ＱＱ：308018629
 * 官网：www.iceui.net
 * 时间：2020-07-13
 * 说明：版权完全归iceui所有，转载和使用请注明版权
 */
; if (typeof ice === 'undefined') throw new Error('本插件依赖ice.js，无法单独使用！');
//加载css
//ice.loadCss(ice.path+'ui/ui.css');

//绑定元素
function $id(id, obj) {
    return (obj || document).getElementById(id);
}
function $class(name, obj) {
    return (obj || document).getElementsByClassName(name);
}
function $name(name, obj) {
    return (obj || document).getElementsByName(name);
}
function $tag(tag, obj) {
    return (obj || document).getElementsByTagName(tag);
}
function $idClass(id, name) {
    var id = document.getElementById(id);
    return id ? id.getElementsByClassName(name) : false;
}
function $idName(id, name) {
    var id = document.getElementById(id);
    return id ? id.getElementsByName(name) : false;
}
function $idTag(id, name) {
    var id = document.getElementById(id);
    return id ? id.getElementsByTagName(name) : false;
}
function log(a) {
    console.log(a)
}
/**
 * table数据请求的封装
 * 
 * @param tableId table的ID
 * @param page 第几页
 */
function query(tableId, page) {
    //查询参数的父元素ID
    var formId = tableId + '_form';
    //分页的父元素ID
    var pageId = tableId + '_page';
    var table = ice('#' + tableId);
    //请求的链接地址
    var url = table.attr('url');
    //每页显示的条数
    var size = parseInt(table.attr('size')) || 10;
    //是否显示分页
    var show_page = table.attr('pager') != 'false';
    //是否高亮显示选中行
    var highlight = table.attr('highlight') != 'false';
    var tbody = table.find('tbody');
    if (tbody.length == 0) {
        ice('#' + tableId).append(ice.c('tbody'));
        tbody = ice('#' + tableId + ' tbody');
    }
    var data = iceui.readForm(formId);
    if (table.attr('data')) {
        var paras = eval('('+table.attr('data')+')');
        for (var key in paras) {
            data[key] = paras[key]; 
        }
    }
    data['page'] = page;
    data['size'] = size;

    iceui.get(url, data, function (datas) {
        var count = datas.count || 0;
        if (show_page && count == 0) {
            tbody.del();
            ice('#' + pageId).html(' ');
            return;
        }
        var htmls = '';
        var json = null, that = null, field = null, render = null;
        var list = datas.list;
        var ths = table.find('thead').find('tr').find('th');
        var sizes = ths.length;
        var num = (page - 1) * size + 1;
        for (var i = 0, lengths = list.length; i < lengths; ++i) {
            json = list[i];
            htmls += '<tr onclick="javascript:clickTr(this, '+highlight+');">';
            for (var j = 0; j < sizes; ++j) {
                that = ice(ths[j]);
                render = that.attr('render');
                if (render) {
                    htmls += '<td>' + (window[render](json)) + '</td>';
                } else {
                    field = that.attr('field');
                    if (field) {
                        htmls += '<td>' + json[field] + '</td>';
                    } else {
                        htmls += '<td>' + (num + i) + '</td>';
                    }
                }
            }
            htmls += '</tr>';
        }
        if (show_page) {
            if (count > size) {
                var quantity = Math.ceil(count / size);
                var pages = '<div class="paging">';
                //首页
                if (page == 1) {
                    pages += '<a href="javascript:void(0);" disabled class="paging-el">上一页</a>';
                    pages += '<a href="javascript:void(0);" class="paging-active">1</a>';
                } else {
                    pages += '<a href="javascript:query(\'' + tableId + '\', ' + (page - 1) + ');" class="paging-prev">上一页</a>';
                    pages += '<a href="javascript:query(\'' + tableId + '\', 1);" class="paging-prev">1</a>';
                }
                //中间部分
                var quantityMax = quantity - 1;
                var pageMax = page + 1;
                var start = (quantity <= 7 || page <= 3) ? 2 : (pageMax < quantityMax) ? (page - 1) : (pageMax == quantityMax ? (page - 2) : (quantity - 4));
                var end = quantity <= 7 ? quantityMax : (page <= 3) ? 5 : (pageMax >= quantityMax ? quantityMax : pageMax);
                if (quantity > 7 && page > 3) {
                    pages += '<a href="javascript:query(\'' + tableId + '\', ' + (page - 2) + ');" class="paging-next">…</a>';
                }
                for (var i = start; i <= end; ++i) {
                    if (i == page) {
                        pages += '<a href="javascript:void(0);" class="paging-active">' + i + '</a>';
                    } else {
                        pages += '<a href="javascript:query(\'' + tableId + '\', ' + i + ');" class="paging-prev">' + i + '</a>';
                    }
                }
                if (quantity > 7 && pageMax < quantityMax) {
                    pages += '<a href="javascript:query(\'' + tableId + '\', ' + (end + 1) + ');" class="paging-next">…</a>';
                }
                //尾页
                if (quantity == page) {
                    pages += '<a href="javascript:void(0);" class="paging-active">' + quantity + '</a>';
                    pages += '<a href="javascript:void(0);" disabled class="paging-el">下一页</a>';
                } else {
                    pages += '<a href="javascript:query(\'' + tableId + '\', ' + quantity + ');" class="paging-prev">' + quantity + '</a>';
                    pages += '<a href="javascript:query(\'' + tableId + '\', ' + (page + 1) + ');" class="paging-next">下一页</a>';
                }
                pages += '</div>';
                ice('#' + pageId).html(pages);
            } else {
                ice('#' + pageId).html(' ');
            }
        }
        tbody.html(htmls);
    });
}
//高亮显示选中行
function clickTr(obj, highlight) {
    if (highlight) {
        var p = ice(obj).parent();
        ice('.bg-gainsboro', p).each(function(i,el){
            ice.delCss(el, 'bg-gainsboro');        
        });
        ice(obj).children('td').each(function(i,el){
            ice.addCss(el, 'bg-gainsboro');        
        });
    }
}
//关闭弹窗
function closePop(){
    ice('#_popup').children('div').del();
}
var iceui = {
    //安装的模块列表
    module: [],
    //内置可安装的模块列表
    moduleList: {
        ui: { path: 'ui/ui', expand: false },                //前端ui
        admin: { path: 'admin/admin', expand: false },       //后台框架
        code: { path: 'code/iceCode', expand: false },       //代码高亮
        date: { path: 'date/iceDate', expand: false },       //时间控件
        editor: { path: 'editor/iceEditor', expand: false }, //富文本编辑器
        drag: { path: 'drag/drag', expand: false },          //拖拽排序
        popup: { path: 'popup/popup', expand: false },       //弹出层
        tree: { path: 'tree/tree', expand: false },          //树形控件
        print: { path: 'print/print', expand: false }        //打印控件
    },
    //生成模块绝对路径
    modulePath: function (name) {
        if (!name) return false;
        //检测是否存在该模块
        if (!iceui.inModule(name)) return;
        name = iceui.moduleList[name].path + '.js';
        //如果路径第一个字符是/说明是根目录
        if (name[0] == '/') return location.origin + name;
        //默认为ice.js当前脚本所在目录
        return ice.path + name;
    },
    //判断模块是否存在
    inModule: function (name) {
        if (name.length && iceui.moduleList[name] || iceui[name]) {
            return true;
        } else {
            console.error('iceui：没有【' + name + '】这个模块');
            return false;
        }
    },
    //引入模块
    inc: function (path, name) {
        if (iceui.inModule(name)) {
            console.error('iceui：【' + name + '】这个模块已存在，请重新命名');
            return false;
        }
        iceui.moduleList[name] = { path: path, expand: true };
        return true;
    },
    //使用模块
    use: function (name, callback) {
        if (typeof name == 'string' && name.length > 0) {
            if (name.indexOf(' ') == -1) {
                //检模块是否已经安装
                if (iceui.module[name]) {
                    callback();
                    return;
                }
                //检测是否存在该模块
                if (!iceui.inModule(name)) return;
                //保存模块
                iceui.module.push(name);
                //安装模块
                ice.loadJs(iceui.modulePath(name), callback);
            } else {
                //利用递归方式完美保证顺序加载模块
                (function rec(url, i) {
                    i = i || 0;
                    //检模块是否已经安装
                    if (iceui.module[url[i]]) {
                        callback();
                        return;
                    }
                    //检测是否存在该模块
                    if (!iceui.inModule(url[i])) return;
                    let u = iceui.modulePath(url[i]);
                    ice.loadJs(u, function () {
                        i++;
                        if (i < url.length) {
                            rec(url, i);
                        } else {
                            callback();
                        }
                    });
                })(name.split(' '));
            }
        }
    },
    //删除
    del: function (url, text) {
        url = typeof (url) == 'object' ? url.href : url;
        text = text || '确认要删除？删除后将无法恢复！';
        ice.pd();
        iceui.prompt({
            content: text,
            btn: ['取消', '确认'],
            yes: function () {
                window.location.href = url;
            }
        });
        return false;
    },
    //提示窗
    pop: function (options, icon = 'default', time = 3000) {
        ice('.pop').del();
        if (typeof options == 'string') {
            options = { title: options, icon: icon, time: time };
        }
        var title = options.title || 0;
        var url = options.url || 0;
        var time = options.time || time;
        var callback = options.callback || function () { };
        //内置图标列表
        var iconList = {
            default: 'ice-face',
            success: 'ice-check-line',
            fail: 'ice-close-line',
            warning: 'ice-about',
            ask: 'ice-help',
            none: '',
        };
        var icon = iconList[options.icon];
        //创建对象
        var id = '_pop' + new Date().getTime();
        var div = ice.c('div');
        div.id = id;
        div.className = 'pop';
        div.innerHTML = '<div class="pop-icon"><i class="icon ' + icon + '"></i></div><div class="pop-title">' + title + '</div>';
        document.body.appendChild(div);
        setTimeout(function () {
            ice.del(div);
            if (url) location.href = url;
            callback();
        }, time);
    },
    //小弹窗
    alert:function(options){
        if(!options.content || !options.content.length)return;
        var btn = options.btn || false;
        var yes = options.yes || false;
        var no = options.no || false;
        //创建对象
        var id = ice.cid('_alert');
        var div = document.createElement('div');
        div.id = id;
        var btnHtml = '<div class="alert-confirm">确定</div><div class="alert-cancel">取消</div>';
        if(btn){
            if(btn[0]){
                btnHtml = `<div class="alert-confirm">${btn[0]}</div>`;
            }
            if(btn[1]){
                btnHtml = `<div class="alert-confirm">${btn[1]}</div><div class="alert-cancel">${btn[0]}</div>`;
            }
        }
        div.innerHTML = `<div class="alert ani-up-in">
            <div class="alert-content">${options.content}</div>
            <div class="alert-footer">
                ${btnHtml}
            </div>
        </div>`;
        document.body.appendChild(div);
        ice('.alert-confirm',div).click(function(){
            ice('.alert',div).hide();
            yes && yes();
        });
        ice('.alert-cancel',div).click(function(){
            ice('.alert',div).hide();;
            no && no();
        });
        ice('.alert',div).show();
    },
    //提示
    prompt: function (options) {
        if (typeof options == 'string') {
            options = { content: options }
        }
        options = options || {};
        var title = options.title || '温馨提示'; //默认不显示标题
        var content = options.content || '未定义'; //默认内容
        var time = options.time || false; //默认不自动关闭弹窗
        var btn = options.btn || false;
        var yes = options.yes || false;
        var no = options.no || false;
        var getTime = new Date().getTime();
        var id_prompt = '_prompt' + getTime;
        var id_close = '_close' + getTime;
        var id_footer = '_footer' + getTime;

        //创建父级div，方便管理所有弹窗
        var prompt = ice.c('div');
        prompt.className = 'prompt';
        document.body.appendChild(prompt);

        //创建按钮
        var btnHtml = '';
        if (btn) for (var i = 0, b; b = btn[i++];) {
            btnHtml += '<span>【' + b + '】</span>';
        }

        //创建模型
        var html = '';
        html += '<div class="prompt-box ani-up-in" id="' + id_prompt + '">';
        html += '<div class="prompt-close" id="' + id_close + '">✕</div>';
        html += '<div class="prompt-title">「' + title + '」</div>';
        html += '<div class="prompt-content">' + content + '</div>';
        html += '<div class="prompt-footer" id="' + id_footer + '">' + btnHtml + '</div>';
        html += '</div>';

        //输出模型
        prompt.innerHTML = html;
        var promptBox = document.getElementById(id_prompt);
        var delT;

        //定义关闭事件
        var close = function () {
            promptBox.className = 'prompt-box ani-up-out';
            setTimeout(function () {
                prompt.parentNode.removeChild(prompt);
            }, 400);
        }
        document.getElementById(id_close).onclick = function () {
            clearTimeout(delT);
            close();
            return false;
        }
        if (time) {
            delT = setTimeout(close, time);
        } else {
            if (!btn) delT = setTimeout(close, 3000);
        }

        var btnObj = document.getElementById(id_footer).getElementsByTagName('span');
        if (btnObj[0]) btnObj[0].onclick = function () {
            close();
            if (no) (no)();
        }
        if (btnObj[1]) btnObj[1].onclick = function () {
            close();
            if (yes) (yes)();
        }
        if (!btnObj[1] && btnObj[0]) btnObj[0].onclick = function () {
            close();
            if (yes) (yes)();
        }
    },
    //注册事件
    reg: function (type, fn) {
        iceui.event[type].push(fn);
    },
    /**
     * form验证
     * Date 2017-09-29
     * submit {Boolean} 表单提交
     */
    check: function (submit) {
        submit = submit || 0;
        var form = ice('.check-form');
        if (form.length) {
            for (var i = 0; i < form.length; i++) {
                form[i].onsubmit = function () {
                    return iceui.check(true);
                }
                form[i].s = ice('.check-submit', form[i])[0];
                if (form[i].s) {
                    form[i].s.i = i;
                    form[i].s.onclick = function () {
                        if (iceui.check(true)) {
                            form[this.i].submit();
                        }
                    }
                }

            }
        }

        //正则表达式
        var check_username = /^[0-9a-zA-Z\u4e00-\u9fa5_]{1,16}$/;
        var check_password = /^[\w]{6,14}$/;
        var check_email = /^([\w\.\-]+)@([\w]+)\.([a-zA-Z]{2,4})$/;

        //邮箱
        var email = ice('.check-email');
        if (email.length) {
            for (var i = 0; i < email.length; i++) {
                email[i].onblur = function () {
                    if (!check_email.test(this.value)) {
                        ice.addCss(this, 'error');
                        iceui.pop('邮箱格式不正确，请检查一下！');
                        return false;
                    } else {
                        ice.delCss(this, 'error');
                    }
                }
                if (submit) {
                    if (!check_email.test(email[i].value)) {
                        ice.addCss(email[i], 'error');
                        iceui.pop('邮箱格式不正确，请检查一下！');
                        return false;
                    } else {
                        ice.delCss(email[i], 'error');
                    }
                }
            }
        }

        //用户名
        var username = ice('.check-username');
        if (username.length) {
            for (var i = 0; i < username.length; i++) {
                username[i].onblur = function () {
                    if (!check_username.test(this.value)) {
                        ice.addCss(this, 'error');
                        iceui.pop('长度为1-14字符，支持中文、大小写字母和下划线，不支持空格！');
                        return false;
                    } else {
                        ice.delCss(this, 'error');
                    }
                }
                if (submit) {
                    if (!check_username.test(username[i].value)) {
                        ice.addCss(username[i], 'error');
                        iceui.pop('长度为1-14字符，支持中文、大小写字母和下划线，不支持空格！');
                        return false;
                    } else {
                        ice.delCss(username[i], 'error');
                    }
                }
            }
        }

        //密码
        var password = ice('.check-password');
        if (password.length) {
            for (var i = 0; i < password.length; i++) {
                password[i].onblur = function () {
                    if (!check_password.test(this.value)) {
                        ice.addCss(this, 'error');
                        iceui.pop('长度为6-14字符，支持数字、大小写字母和下划线，不支持空格！');
                        return false;
                    } else {
                        ice.delCss(this, 'error');
                    }
                }
                if (submit) {
                    if (!check_password.test(password[i].value)) {
                        ice.addCss(password[i], 'error');
                        iceui.pop('长度为6-14字符，支持数字、大小写字母和下划线，不支持空格！');
                        return false;
                    } else {
                        ice.delCss(password[i], 'error');
                    }
                }
            }
        }

        //确认密码
        var confirm = ice('.check-confirm');
        if (confirm.length) {
            for (var i = 0; i < confirm.length; i++) {
                confirm[i].i = i;
                confirm[i].onblur = function () {
                    if (this.value != password[this.i].value) {
                        ice.addCss(this, 'error');
                        iceui.pop('两次密码输入不正确！');
                        return false;
                    } else {
                        ice.delCss(this, 'error');
                    }
                }
                if (submit) {
                    if (confirm[i].value != password[i].value) {
                        ice.addCss(confirm[i], 'error');
                        iceui.pop('两次密码输入不正确！');
                        return false;
                    } else {
                        ice.delCss(confirm[i], 'error');
                    }
                }
            }
        }

        //通用空选项
        var empty = ice('.check-empty');
        if (empty.length) {
            for (var i = 0; i < empty.length; i++) {
                empty[i].onblur = function () {
                    if (this.value.replace(/(^\s*)|(\s*$)/g, "") == '') {
                        ice.addCss(this, 'error');
                        iceui.pop('不能为空，请输入内容！');
                        return false;
                    } else {
                        ice.delCss(this, 'error');
                    }
                }
                if (submit) {
                    if (empty[i].value.replace(/(^\s*)|(\s*$)/g, "") == '') {
                        ice.addCss(empty[i], 'error');
                        iceui.pop('不能为空，请输入内容！');
                        return false;
                    } else {
                        ice.delCss(empty[i], 'error');
                    }
                }
            }
        }
        return true;
    },
    //单文件上传
    singleFileUpload: function () {
        var magicFile = ice('.iceUpload-single');
        if (magicFile.length) {
            magicFile.each(function () {
                var input = ice('input', this)[0];
                var btn = ice('.btn', this)[0];
                input.onchange = function () {
                    //截取文件名称
                    btn.innerHTML = this.value.substring(this.value.lastIndexOf("\\") + 1);
                }
                btn.onclick = function () {
                    input.click();
                    return false;
                }
            })
        }
    },
    /**
     * 读取数据
     * 
     * @param id 父元素ID
     * @returns json格式的子元素键值对
     */
    readForm: function (id) {
        var obj = null;
        var json = new Object();
        var ids = '#' + id + ' input';
        var arr = ice(ids);
        var lengths = arr.length;
        for (var i = 0; i < lengths; ++i) {
            obj = arr[i];
            if(obj.name){
                json[obj.name] = obj.value;
            }
        }
        ids = '#' + id + ' select';
        arr = ice(ids);
        lengths = arr.length;
        for (var i = 0; i < lengths; ++i) {
            obj = arr[i];
            if(obj.name){
                json[obj.name] = obj.value;
            }
        }
        ids = '#' + id + ' textarea';
        arr = ice(ids);
        lengths = arr.length;
        for (var i = 0; i < lengths; ++i) {
            obj = arr[i];
            if(obj.name){
                json[obj.name] = obj.value;
            }
        }

        return json;
    },
    /**
     * 验证数据格式是否正确
     * 
     * @param id 父元素ID
     * @returns true输入的值符合验证规则,false输入的值不符合验证规则
     */
    validateForm: function (id) {
        var ids = '#' + id + ' input';
        var arr = ice(ids);
        var lengths = arr.length;
        for (var i = 0; i < lengths; ++i) {
            if (!iceui.validateElement(ice(arr[i]))) {
                return false;
            }
        }
        ids = '#' + id + ' select';
        arr = ice(ids);
        lengths = arr.length;
        for (var i = 0; i < lengths; ++i) {
            if (!iceui.validateElement(ice(arr[i]))) {
                return false;
            }
        }
        ids = '#' + id + ' textarea';
        arr = ice(ids);
        lengths = arr.length;
        for (var i = 0; i < lengths; ++i) {
            if (!iceui.validateElement(ice(arr[i]))) {
                return false;
            }
        }

        return true;
    },
    /**
     * 验证元素格式是否正确
     * 
     * @param obj 元素实体
     * @returns true输入的值符合验证规则,false输入的值不符合验证规则
     */
    validateElement: function (obj) {
        var rule = obj.attr('rule');
        if (rule == false) {
            return true;
        }
        var arrs = null, arr = null, txt = '';
        var val = obj.val();
        var rules = rule.split(';');
        var lengths = rules.length;
        for (var i = 0; i < lengths; ++i) {
            arrs = rules[i].split(':');
            arr = arrs[0];
            if (arr == 'txt') {
                txt = arrs[1];
                continue;
            } else if (arr == 'required') {
                if (val == '') {
                    obj.addCss('error');
                    iceui.pop({ title: txt + '不能为空', icon: 'warning' });
                    return false;
                }
            } else if (arr == 'length') {
                if (val.length > arrs[1]) {
                    obj.addCss('error');
                    iceui.pop({ title: txt + '限制输入' + arrs[1] + '个字符', icon: 'warning' });
                    return false;
                }
            } else if (arr == 'int') {
                if (val.length > 0 && !(/^[0-9]+$/.test(val))) {
                    obj.addCss('error');
                    iceui.pop({ title: txt + '限制输入整数', icon: 'warning' });
                    return false;
                }
            } else if (arr == 'double') {
                if (val.length > 0 && !(/^[0-9]+(.[0-9]{0,2})?$/.test(val))) {
                    obj.addCss('error');
                    iceui.pop({ title: txt + '限制输入两位小数', icon: 'warning' });
                    return false;
                }
            } else if (arr == 'identity') {
                if (val.length > 0 && !(/(^\d{15}$)|(^\d{17}([0-9]|X|x)$)/.test(val))) {
                    obj.addCss('error');
                    iceui.pop({ title: txt + '格式不正确', icon: 'warning' });
                    return false;
                }
            }
        }
        if (obj.hasCss('error')) {
            obj.delCss('error');
        }

        return true;
    },
    /**
     * 清空指定ID下的所有子元素的数据
     * 
     * @param id 父元素ID
     */
    clearForm: function (id) {
        var ids = '#' + id + ' input';
        var arr = ice(ids);
        var lengths = arr.length;
        for (var i = 0; i < lengths; ++i) {
            arr[i].value = '';
        }
        ids = '#' + id + ' select';
        arr = ice(ids);
        lengths = arr.length;
        for (var i = 0; i < lengths; ++i) {
            ice(arr[i]).val('');
        }
        ids = '#' + id + ' textarea';
        arr = ice(ids);
        lengths = arr.length;
        for (var i = 0; i < lengths; ++i) {
            arr[i].value = '';
        }
    },
    //数据加载动画
    loading: function () {
        if (document.getElementById('loading_2333') != null) {
            return;
        }

        var div = ice.c('div');
        div.id = 'loading_2333';
        div.setAttribute('style', 'opacity: 0.5; z-index: 999990;');
        div.innerHTML = '<div class="loading"><div class="loader-2"></div></div>';
        document.body.appendChild(div);
    },
    /**
     * get请求封装
     * 
     * @param url 请求的链接
     * @param data 请求的参数
     * @param func 处理返回结果的方法,服务器是否发生错误都会调用
     * @param sync 是否是异步请求
     * @param dataType 返回的数据类型
     */
    get: function (url, data, func, sync, dataType) {
        iceui.loading();
        //是否需要保持加载状态
        var keepLoading = keepLoading || false;
        ice.ajax({
            url: url,
            type: 'get',
            data: data,
            json: dataType != 'text',
            sync: sync != false,
            success: func,
            error: func,
            complete: function (status) {
                if (keepLoading) {
                    return;
                }
                ice('#loading_2333').del();
                if (status == 0 || status >= 400) {
                    iceui.pop({title: '网络异常, 请稍后重试', icon: 'warning'});
                }
            }
        });
    },
    /**
     * post请求封装
     * 
     * @param url 请求的链接
     * @param data 请求的参数
     * @param func 处理返回结果的方法,服务器是否发生错误都会调用
     * @param sync 是否是异步请求
     * @param dataType 返回的数据类型
     */
    post: function (url, data, func, sync, dataType) {
        iceui.loading();
        //是否需要保持加载状态
        var keepLoading = keepLoading || false;
        ice.ajax({
            url: url,
            type: 'post',
            data: data,
            json: dataType != 'text',
            sync: sync != false,
            success: func,
            error: func,
            complete: function (status) {
                if (keepLoading) {
                    return;
                }
                ice('#loading_2333').del();
                if (status == 0 || status >= 400) {
                    iceui.pop({title: '网络异常, 请稍后重试', icon: 'warning'});
                }
            }
        });
    },
    //美化所有的select
    diyAllSel: function () {
        ice('select').each(function () {
            var id = this.id;
            if (!id) {
                var name = this.name || 'cid';
                id = ice.cid(name);
                this.id = id;
            }
            iceui.diySel(id);
        });
    },
    /**
     * 美化指定id的select
     * 
     * @param id select的ID
     */
    diySel: function (id) {
        var that = ice('#' + id);
        //模拟下拉列表
        var div = ice('#div_' + id);
        if (div.length == 0) {
            var _html = '<div id="div_' + id + '" class=\"' + that.attr('class') + '\">';
            _html += '<div id="subdiv_' + id + '" class=\"sel_txt\">' + ice('#' + id + ' option[value="' + that.val() + '"]').text() + '</div>';
            _html += '<ul id="ul_' + id + '" class=\"sel_ul\"></ul>';
            _html += '</div>';
            that.after(_html);
            that.hide();
        } else {
            ice('#subdiv_' + id).text(ice('#' + id + ' option[value="' + that.val() + '"]').text());
        }
        var _html = '';
        that.children('option').each(function () {
            var option = ice(this);
            if (that.val() == option.val()) {
                _html += '<li data-value=\"' + option.val() + '\" class=\"cur\">' + option.text() + '</li>';
            } else {
                _html += '<li data-value=\"' + option.val() + '\">' + option.text() + '</li>';
            }
        });
        var select = ice('#div_' + id);
        var select_text = ice('#subdiv_' + id);
        var select_ul = ice('#ul_' + id);
        select_ul.html(_html);
        //下拉列表操作
        select.click(function () {
            if (!ice(that).attr('disabled')) {
                select_ul.slideToggle();
            }
        });
        select_ul.children('li').each(function () {
            ice(this).click(function () {
                var li = ice(this);
                li.siblings('.cur').delCss('cur');
                var val = li.addCss('cur').attr('data-value');
                if (val != that.val()) {
                    select_text.text(li.text());
                    that.val(val);
                    //回调函数
                    that.attr('change') && window[that.attr('change')](val, li.text(), that[0]);
                }
            });
        });
    },
};
//事件
iceui.event = [];
iceui.event['scroll'] = []; //监听滚动条滚动
iceui.event['resize'] = []; //监听窗口大小改变
iceui.event['load'] = [];   //onload后，只执行一次
iceui.event['node'] = [];   //onload后，遍历所有节点，只执行一次
//导航
iceui.nav = {};
//导航滑动线默认开启
iceui.nav.line = true;

var i;
//将事件统一执行，不但代码美观，性能还有一定的提升。
//监听滚动条滚动
ice.on(window, 'scroll', function () {
    var scroll = ice.scroll();
    var i = 0, len = iceui.event['scroll'].length;
    for (; i < len; i++) {
        iceui.event['scroll'][i](scroll);
    }
});
//监听窗口大小改变
ice.on(window, 'resize', function (e) {
    iceui.webW = ice.web().w;
    iceui.webH = ice.web().h;
    var i = 0, len = iceui.event['resize'].length;
    for (; i < len; i++) {
        iceui.event['resize'][i](ice.web().w, ice.web().h);
    }
});
//监听程序加载完以后
ice.on(window, 'load', function () {
    var i = 0, len = iceui.event['load'].length, s = iceui.event['node'].length;
    for (; i < len; i++) {
        iceui.event['load'][i]();
    }
    ice.eachNode(window.document, function () {
        for (i = 0; i < s; i++) {
            iceui.event['node'][i](this);
        }
    })
    if (ice.runtime) console.timeEnd('ice');
});

//初始化iceui框架的前端页面
ice.ready(function () {
    //定义变量
    iceui.webW = ice.web().w;
    iceui.webH = ice.web().h;

    //------------------------------------------------------------------------------------+
    // 前端动画交互
    //------------------------------------------------------------------------------------+
    // 时间：2018-04-25
    //------------------------------------------------------------------------------------+
    //loading加载动画
    iceui.body = ice('body');
    if (iceui.body.attr('data-load')) {
        var load = ice('.loading');
        if (load.length) {
            iceui.reg('load', function () {
                load.addCss('loading-close');
            });
        } else {
            var loadType = iceui.body.attr('data-load-type');
            loadType = loadType ? loadType : 2;
            var loadDiv = ice.c('div');
            loadDiv.className = 'loading';
            loadDiv.innerHTML = '<div class="loader-' + loadType + '"></div>';
            iceui.body.append(loadDiv);
            iceui.reg('load', function () {
                loadDiv.className = 'loading loading-close';
            });
        }
    }

    //导航超过屏幕高度或banner高度后设置背景颜色
    iceui.navAutoBg = ice('.auto-navbg');
    iceui.banner = ice('.banner');
    if (iceui.navAutoBg.length) {
        +function () {
            let a = iceui.navAutoBg.attr('data-setAutoBg');
            var h = a == 'wh' ? iceui.webH : false;
            if (!h) {
                if (!iceui.banner.length) return false;
                h = iceui.banner[0].offsetTop + iceui.banner[0].offsetHeight;
            }
            ice.on(window, 'scroll', function () {
                if (ice.scroll().y > h - iceui.navAutoBg[0].offsetHeight) {
                    iceui.navAutoBg.addCss('auto-navbg-on');
                } else {
                    iceui.navAutoBg.delCss('auto-navbg-on');
                }
            });
        }();
    }

    //自动高度
    iceui.autoHeight = ice('.auto-height');
    if (iceui.autoHeight) {
        iceui.autoHeight.each(function () {
            this.style.height = iceui.webH + 'px';
        });
    }

    //自动高度
    ice('.submit').click(function () {
        (function s(z) {
            var p = ice(z).parent();
            if (p) {
                if (p.tagName == 'FORM') {
                    p.submit();
                } else {
                    s(p);
                }
            }
        })(this);
    });

    //滚动条加载class事件
    //注册滚动条滚动事件
    iceui.scroll = [];
    iceui.reg('node', function (a) {
        var scroll = ice(a);
        var css = scroll.attr('data-scroll-class'); //为空则默认不进行任何操作，这里需要添加class，注意，只能为class！不能为id？抱歉，使用id没有意义
        if (css) {
            var top = scroll.attr('data-scroll-top');     //为空则默认为元素的总高
            var delay = scroll.attr('data-scroll-delay'); //为空则默认为0，单位ms
            var type = scroll.attr('data-scroll-type');   //为空则默认为fixed(固定)，有效值：auto(随滚动条自动变化)，fixed(只执行一次，就固定了)
            var view = scroll.attr('data-scroll-view');   //为空则默认为bottom(视口上面)，有效值：top(元素在视口上面时触发)，bottom(元素在视口下面时触发)
            var info = [];
            info['delay'] = delay ? parseInt(delay) : 0;
            info['type'] = type ? type : 'fixed';
            info['view'] = view ? view : 'bottom';
            info['class'] = css;
            if (top == 'view') top = ice.web().h;
            info['top'] = top ? parseInt(top) : scroll.page().top;
            if (!top && info['view'] == 'bottom') info['top'] -= iceui.webH;
            info['el'] = scroll;
            iceui.scroll.push(info);
        }
    });
    //注册滚动条滚动事件
    iceui.reg('scroll', function (scroll) {
        ice.each(iceui.scroll, function () {
            if (this.top <= scroll.y) {
                (function (a) { setTimeout(function () { a.el.addCss(a.class) }, a.delay) })(this);
            } else {
                if (this.type == 'auto') this.el.delCss(this.class);
            }
        });
    });

    //文字单个逐步加载动画
    var aniOneArr = ice('.ani-one-in');
    if (aniOneArr.length) {
        aniOneArr.each(function () {
            var str = this.innerHTML.split('');
            for (var a = 0; a < str.length; a++) {
                if (str[a].length > 0) str[a] = '<span style="transition-delay:' + (a / 10) + 's;">' + str[a] + '</span>';
            }
            this.innerHTML = str.join('');
            //根据滚动条判断动画项是否出现在视口里面
            if (ice.page(this).top <= ice.scroll().y + iceui.webH) ice.addCss(this, 'ani-show');
        });
    }

    //导航滚动逐步加载动画
    var aniArr = ice('.ani');
    if (aniArr.length) {
        aniArr.each(function () {
            this.s = ice.attr(this, 'data-ani-delay');
            this.s = this.s ? parseInt(this.s) : 100;
            this.t = ice.page(this).top - iceui.webH - this.offsetHeight;
            //根据滚动条判断动画项是否出现在视口里面
            if (this.t <= ice.scroll().y) {
                (function (a) {
                    setTimeout(function () { ice.addCss(a, 'ani-show') }, a.s);
                })(this);
            }
        });
        //根据滚动条判断动画项是否出现在视口里面
        iceui.reg('scroll', function (e) {
            aniArr.each(function () {
                if (this.t <= e.y) {
                    (function (a) {
                        setTimeout(function () { ice.addCss(a, 'ani-show') }, a.s);
                    })(this);
                }
            });
        });
    }

    //导航滚动数字变化加载
    var aniNum = ice('.ani-num');
    if (aniNum.length) {
        var aniNumFn = function (el, e) {
            if (el.rollNum) {
                if (el.t <= e.y) {
                    (function (a) {
                        setTimeout(function () {
                            var num = a.num;
                            var s = parseInt(num / 30); //取整，用来均衡所有数字的递增速度
                            var i = 0;
                            var t = setInterval(function () {
                                i += s ? s : 1;
                                if (i < num) {
                                    a.innerHTML = i;
                                } else if (i === num) {
                                    a.innerHTML = i;
                                    clearInterval(t);
                                    a.rollNum = false;
                                } else {
                                    a.innerHTML = num;
                                    clearInterval(t);
                                    a.rollNum = false;
                                }
                            }, 30);
                        }, a.s);
                    })(el);
                }
            }
        };
        aniNum.each(function () {
            this.num = this.innerHTML;
            this.s = ice.attr(this, 'data-ani-delay');
            this.s = this.s ? parseInt(this.s) : 100;
            this.t = ice.page(this).top - iceui.webH;
            this.rollNum = true;
            //根据滚动条判断动画项是否出现在视口里面
            aniNumFn(this, ice.scroll());
        });
        //根据滚动条判断动画项是否出现在视口里面
        iceui.reg('scroll', function (e) {
            aniNum.each(function () {
                aniNumFn(this, e);
            });
        });
    }

    //弹出层
    iceui.reg('node', function (e) {
        //打开某个弹窗
        var open = ice.attr(e, 'data-popup-open');
        if (open) {
            var openObj = $id(open);
            if (openObj) {
                e.onclick = function () {
                    ice(openObj).toggleCss('none');
                    ice.sp();
                    ice('.popup-close', openObj).click(function () {
                        ice(openObj).toggleCss('none');
                    })
                }
            }
        }
    });

    //视差背景图
    iceui.reg('node', function (a) {
        var url = ice.attr(a, 'data-img-parallax');
        if (url) {
            a.style.backgroundImage = 'url(' + url + ')';
            ice.addCss(a, 'data-img-parallax');
        }
    });

    //表格排序
    ice.use('table', function () {
        iceui.reg('node', function (a) {
            var sort = ice.attr(a, 'data-table-sort');
            if (sort) ice.table({ el: a, sort: sort == 'true' ? false : sort });
        });
    });


    //------------------------------------------------------------------------------------+
    // 核心表单控件
    //------------------------------------------------------------------------------------+
    // 时间：2018-04-27
    //------------------------------------------------------------------------------------+
    //图标按钮开关
    ice('.toggle-menu').on('click', function () { ice(this).toggleCss('open') }); //菜单图标
    ice('.toggle-more').on('click', function () { ice(this).toggleCss('open') }); //更多图标

    //导航下拉菜单
    iceui.nav.toggle = ice('.nav-wap .toggle-menu')[0];
    iceui.nav.menu = ice('.nav-menu')[0];
    ice('.nav-list li').on('click', function () {
        ice('.click', this).each(function (i) {
            ice(this).delCss('click');
        });
        ice(this).toggleCss('click');
        ice.sp();
    });

    if (iceui.nav.menu && iceui.nav.line) {
        //导航条滑动
        +function () {
            var line = ice.c('div');
            line.className = 'nav-line';
            iceui.nav.menu.appendChild(line);
            var timer, i, n, m, speed = 0, changeWidth, sports, obj = ice('.nav-list li'), active = ice('.nav-list .active')[0];
            sports = function (n, m) {
                timer = setInterval(function () {
                    speed = (n - line.offsetLeft) / 10;
                    speed = speed > 0 ? Math.ceil(speed) : Math.floor(speed);
                    if (line.offsetLeft === n) {
                        clearInterval(timer);
                    } else {
                        line.style.left = line.offsetLeft + speed + 'px';
                    }
                    changeWidth = m - line.offsetWidth;
                    changeWidth = changeWidth > 0 ? Math.ceil(speed) : Math.floor(speed);
                    line.style.width = m + changeWidth + 'px';
                }, 20);
            }
            setTimeout(function () {
                if (!active) {
                    active = [];
                    active.offsetWidth = obj[0].offsetWidth;
                    active.offsetLeft = obj[0].offsetLeft;
                }
                sports(active.offsetLeft, active.offsetWidth);
            }, 500);
            for (i = 0; i < obj.length; i += 1) {
                obj[i].onmouseover = function () {
                    clearInterval(timer);
                    sports(this.offsetLeft, this.offsetWidth);
                };
                obj[i].onmouseout = function () {
                    clearInterval(timer);
                    sports(active.offsetLeft, active.offsetWidth);
                };
            }
        }();
    };
    var menu_dropdown = ice('.nav .nav-dropdown');
    if (iceui.nav.toggle && iceui.nav.menu) {
        iceui.nav.toggle.onclick = function () {
            ice.toggle(iceui.nav.menu);
        }
        iceui.reg('resize', function (w, h) {
            iceui.nav.menu.style.display = w > 768 ? 'block' : 'none';
            ice.delCss(iceui.nav.toggle, 'open');
        })
        //下拉菜单居中
        if (iceui.webW > 768) {
            if (menu_dropdown.length) {
                for (var i = 0; i < menu_dropdown.length; i++) {
                    menu_dropdown[i].style.marginLeft = (menu_dropdown[i].parentNode.offsetWidth - 150) / 2 + "px";
                }
            }
        }
    }
    if (iceui.nav.menu) {
        //给拥有下拉菜单的li添加标识，显示箭头
        menu_dropdown.each(function () {
            ice.addCss(this.parentNode, 'dropdown');
        });
    }

    //下拉菜单
    var dropdown_toggle = ice('.dropdown .dropdown-toggle');
    if (dropdown_toggle.length) {
        for (var i = 0, dropdown; dropdown = dropdown_toggle[i++];) {
            ice.on(dropdown, 'click', function (e) {
                var a = this.parentNode;
                if (ice.hasCss(a, 'open')) {
                    ice.delCss(a, 'open');
                } else {
                    ice.delCss(ice('.dropdown'), 'open');
                    ice.addCss(a, 'open');
                }
                ice.on(a, 'click', function (e) {
                    ice.sp(e);
                });
                ice.pd(e);
            });
            if (ice.hasCss(dropdown, 'dropdown-hover')) {
                ice.on(dropdown, 'mouseover', function (e) {
                    ice.addCss(this.parentNode, 'open');
                    ice.sp(e);
                });
                ice.on(dropdown, 'mouseout', function (e) {
                    ice.delCss(this.parentNode, 'open');
                });
                ice.on(ice(dropdown).next(), 'mouseover', function (e) {
                    ice.addCss(this.parentNode, 'open');
                });
                ice.on(ice(dropdown).next(), 'mouseout', function (e) {
                    ice.delCss(this.parentNode, 'open');
                });
            }
        }
    }
    //点击任何区域关闭下拉菜单
    ice.on(iceui.body, 'click', function (e) {
        ice.delCss(ice('.dropdown'), 'open');
    });


    /** ----------------------选项卡切换---------------------- **/
    var tab = ice('.tab');
    if (tab.length) {
        tab.each(function (ti, el) {
            var menuBox = el.children[0],    //获取菜单容器
                contentBox = el.children[1]; //获取内容容器
            if (menuBox && contentBox) {
                var move, active = 0, isMove = 1, j = { width: 0, left: 0 },
                    menu = ice('a', menuBox),        //获取所有菜单
                    content = contentBox.children,  //获取所有内容
                    setLine = function (obj, move) { j.width = obj[j.swh] + 'px'; j.left = obj[j.slt] + 'px'; move.style[j.wh] = j.width; move.style[j.lt] = j.left; };
                if (menu.length !== content.length) return;
                //新建移动的线-判断是否存在move的html
                if (ice('.tab-move', menuBox).length) {
                    move = ice('.tab-move', menuBox)[0];
                    if (ice.attr(move, 'style')) isMove = 0;
                } else {
                    move = ice.c('div');
                    move.className = 'tab-move';
                    menuBox.prepend(move);
                }
                //判断是否为侧栏风格
                if (ice.hasCss(el, 'tab-sidebar')) {
                    j.wh = 'height', j.lt = 'top', j.swh = 'offsetHeight', j.slt = 'offsetTop';
                } else {
                    j.wh = 'width', j.lt = 'left', j.swh = 'offsetWidth', j.slt = 'offsetLeft';
                }
                menu.each(function (mi, m) {
                    //判断是否有激活的菜单
                    if (m.className == 'active') {
                        if (isMove) setLine(m, move);
                        content[mi].className = 'tab-content active';
                        active = 1;
                    }
                    //菜单点击事件
                    this.onclick = function (e) {
                        //是否为#，不是的话当可以当a标签跳转
                        if (ice.attr(this, 'href') == '#') {
                            ice(menu).delCss('active');
                            ice(content).delCss('active');
                            ice(this).addCss('active');
                            ice(content).s(mi).addCss('active');
                            setLine(this, move);
                            ice.sp(e);
                            return false;
                        }
                    }
                    //移动到菜单
                    this.onmouseover = function () {
                        move.style[j.wh] = m[j.swh] + 'px';
                        move.style[j.lt] = m[j.slt] + 'px';
                    }
                    //移出菜单
                    this.onmouseout = function () {
                        move.style[j.wh] = j.width;
                        move.style[j.lt] = j.left;
                    }
                });
                //如果没有默认的激活菜单，则默认激活第一个菜单
                if (!active) {
                    menu[0].className = 'active';
                    content[0].className = 'tab-content active';
                    setLine(menu[0], move);
                }
            }
            ice.addCss(el, 'tab-show');
        });
    }

    //在线客服
    iceui.toolbar = iceui.toolbar || {};
    if (iceui.toolbar.qq || iceui.toolbar.wx || iceui.toolbar.tel || iceui.toolbar.scan || iceui.toolbar.top) {
        var html = '';
        if (iceui.toolbar.qq || iceui.toolbar.wx || iceui.toolbar.tel) {
            html += '<div id="toolbar-contact">';
            html += '<i class="icon ice-custom-service"></i>';
            html += '<div id="toolbar-contact-box" ' + (iceui.toolbar.contact ? 'style="display: block;"' : '') + '>';
            html += '<div class="contact-title"><i class="icon ice-custom-service"></i>在线客服<i id="toolbar-contact-close" class="icon ice-close-line"></i></div>';
            //微信
            if (iceui.toolbar.wx) {
                //html += '<div class="contact-tel-title"><i class="icon ice-weixin"></i>微信客服</div>';
                html += '<ul class="contact-qq-list">';
                for (var i = 0, wx; wx = iceui.toolbar.wx[i++];) {
                    html += '<li><a href="javascript:;"><i class="icon ice-weixin"></i>' + wx + '</a></li>';
                }
                html += '</ul>';
            }
            //qq
            if (iceui.toolbar.qq) {
                //html += '<div class="contact-tel-title"><i class="icon ice-qq"></i>QQ客服</div>';
                html += '<ul class="contact-qq-list">';
                for (var i = 0, qq; qq = iceui.toolbar.qq[i++];) {
                    html += '<li><a href="tencent://message/?uin=' + qq + '&amp;Site=uelike&amp;Menu=yes"><i class="icon ice-qq"></i>' + qq + '</a></li>';
                }
                html += '</ul>';
            }
            //手机号
            if (iceui.toolbar.tel) {
                html += '<div class="contact-tel-title"><i class="icon ice-tel"></i>联系电话</div>';
                html += '<ul class="contact-tel-list">';
                for (var i = 0, tel; tel = iceui.toolbar.tel[i++];) {
                    html += '<li><a href="tel:' + tel + '">' + tel + '</a></li>';
                }
                html += '</ul>';
            }
            html += '</div>';
            html += '</div>';
        }
        if (iceui.toolbar.scan) {
            html += '<div id="toolbar-scan">';
            html += '<i class="icon ice-erweima"></i>';
            html += '<div id="toolbar-scan-popup"><div><img src="' + iceui.toolbar.scan + '" alt=""/><span>扫一扫进入手机端</span></div></div>';
            html += '</div>';
        }
        if (iceui.toolbar.top) {
            html += '<div id="toolbar-top"><i class="icon ice-arrow-line-t"></i></div>';
        }
        var toolbar = ice.c('div');
        toolbar.id = 'toolbar';
        toolbar.innerHTML = html;
        iceui.body.append(toolbar);
        if (iceui.toolbar.qq || iceui.toolbar.wx || iceui.toolbar.tel) {
            toolbar.contact = ice('#toolbar-contact')[0];
            toolbar.contactBox = ice('#toolbar-contact-box')[0];
            toolbar.contactClose = ice('#toolbar-contact-close')[0];
            toolbar.contactClose.onclick = function (e) {
                ice.sp(e);
                ice.delCss(toolbar.contactBox, 'ani-right-in');
                ice.addCss(toolbar.contactBox, 'ani-right-out');
                setTimeout(function () { toolbar.contactBox.style.display = null; }, 300);
            }
            toolbar.contact.onclick = function () {
                toolbar.contactBox.style.display = "block";
                ice.delCss(toolbar.contactBox, 'ani-right-out');
                ice.addCss(toolbar.contactBox, 'ani-right-in');
            }
        }
        if (iceui.toolbar.scan) {
            toolbar.scan = ice('#toolbar-scan');
            if (toolbar.scan.length) {
                toolbar.scanPopup = ice('#toolbar-scan-popup')[0];
                toolbar.scan[0].onclick = function () {
                    toolbar.scanPopup.style.display = 'block';
                    toolbar.scanPopup.className = 'ani-up-in';
                }
                toolbar.scanPopup.onclick = function (e) {
                    ice.sp(e);
                    this.className = 'ani-up-out';
                    setTimeout(function () { toolbar.scanPopup.style.display = null; }, 300);
                }
            }
        }
        if (iceui.toolbar.top) {
            // 获取置顶对象
            toolbar.top = ice('#toolbar-top')[0];
            //根据滚动条判断动画项是否出现在视口里面
            iceui.reg('scroll', function (e) {
                if (e.y > 300) {
                    toolbar.top.style.display = 'block';
                    toolbar.top.className = 'ani-down-in';
                } else {
                    toolbar.top.style.display = 'none';
                }
            });
            // 置顶对象点击事件
            toolbar.top.onclick = function () {
                var timer = setInterval(function () {
                    window.scrollBy(0, -50);
                    if (ice.scroll().y == 0) clearInterval(timer);
                }, 2);
            }
        }
    }


    //单文件上传
    iceui.singleFileUpload();

    //多图片上传
    var imgBox = ice('.iceUpload-img');
    if(imgBox.length){
        imgBox.each(function(){
            var inputName = ice(this).attr('data-name');
            var inputAccept = ice(this).attr('data-accept');
            var uploadFn = ice(this).attr('data-upload');
            var closeFn = ice(this).attr('data-del');
            var completeFn = ice(this).attr('data-complete');
            var uploadUrl = ice(this).attr('data-url');
            if(!ice('.iceUpload-list',this).length)this.innerHTML='<div class="iceUpload-list" style="display:none;"></div>'+this.innerHTML;
            var imgList = ice('.iceUpload-list',this)[0];
            var imgSrc=[];

            ice('.iceUpload-close',imgList).click(function(){
                var src = ice('img',this.parentNode)[0].src;
                ice.del(this.parentNode);
                imgSrc=[];
                ice('img',imgList).each(function(){
                    imgSrc.push(ice(this).attr('src'));
                });
                closeFn && window[closeFn] && window[closeFn](src,imgSrc);
                completeFn && window[completeFn] && window[completeFn](src,imgSrc);
                //重新排序
                var order = ice('.iceUpload-order',imgList);
                order.each(function(s){
                    this.innerHTML = s+1;
                });
                if(!order.length)imgList.style.display='none';
            });

            var imgBtn = ice('.btn',this)[0];
            if(imgBtn){
                imgBtn.onclick=function(){
                    if(!inputName) return iceui.pop('需设置name属性','warning');
                    if(!uploadUrl) return iceui.pop('需设置url上传地址属性','warning');
                    if(input)ice.del(input),input=null;
                    //创建input
                    var input = ice.c('input');
                    input.type='file';
                    input.multiple=true;
                    input.name = inputName;
                    input.accept = inputAccept ? inputAccept : 'image/*';
                    input.onchange=function(){
                        //获取上传文件的扩展名
                        var ext = input.value;
                        console.log(ext)
                        var extIndex = ext.lastIndexOf('.');
                        ext = ext.substring(extIndex+1);
                        if(ext!='jpg' && ext!='jpeg' && ext!='gif' && ext!='png' && ext!='bmp'){
                            alert('仅支持上传jpg、gif、png等图片格式的文件');
                            ice.del(input);
                            return;
                        }
                        ice.each(this.files, function () {
                            var item = ice.c('div');
                            item.className="iceUpload-item";
                            var order = ice.c('div');
                            order.className="iceUpload-order"
                            var info = ice.c('div');
                            info.className="iceUpload-info";
                            var img = ice.c('img');
                            var close = ice.c('div');
                            close.innerHTML='✕';
                            close.className='iceUpload-close';
                            var load = ice.c('div');
                            load.className="iceUpload-load";
                            load.innerHTML='<div class="loader-2"></div>';
                            var res = new FileReader();
                            res.readAsDataURL(this);
                            res.onload = function (oFREvent) {
                                img.src = oFREvent.target.result;
                                imgList.removeAttribute('style');
                            };

                            //最终输出
                            info.appendChild(img);
                            item.appendChild(order);
                            item.appendChild(info);
                            item.appendChild(close);
                            item.appendChild(load);
                            imgList.appendChild(item);
                            //获取所有图片列表
                            imgItem = ice('.iceUpload-item',imgList);
                            //图片排序
                            order.innerHTML=imgItem.length;
                            close.onclick=function(){
                                var src = ice(img).attr('src');
                                ice.del(item);
                                imgSrc=[];
                                ice('img',imgList).each(function(){
                                    imgSrc.push(ice(this).attr('src'));
                                });
                                closeFn && window[closeFn] && window[closeFn](src,imgSrc);
                                completeFn && window[completeFn] && window[completeFn](src,imgSrc);
                                //重新排序
                                var imgOrder=ice('.iceUpload-order',imgList);
                                if(imgOrder.length){
                                    for(var a=0,o;o=imgOrder[a++];){o.innerHTML=a;}
                                }else{
                                    imgList.style.display='none';
                                }
                            }
                            var formData = new FormData();
                            formData.append(input.name,this);
                            ice.ajax({
                                url: uploadUrl,
                                data: formData,
                                success: function (res) {
                                    if (!res.error) {
                                        img.src = res.url;
                                        ice(load).hide();
                                        imgList.removeAttribute('style');
                                        imgSrc = [];
                                        ice('img',imgList).each(function(){
                                            var src = ice(this).attr('src');
                                            if(src.substring(0,5) != 'data:')imgSrc.push(src); //过滤base64图片
                                        });
                                        uploadFn && window[uploadFn](res.url,imgSrc);
                                        completeFn && window[completeFn] && window[completeFn](res.url,imgSrc);
                                    }else{
                                        ice(item).addCss('iceUpload-error');
                                        ice('.iceUpload-order',item).html(res.error);
                                        ice(load).hide();
                                        alert(res.error);
                                    }
                                }
                            })
                        });
                    }
                    input.click();
                    return false;
                }
            }
        });
    }

    //多附件上传
    var fileBox = ice('.iceUpload-file');
    if(fileBox.length){
        fileBox.each(function(){
            var inputName = ice(this).attr('data-name');
            var inputAccept = ice(this).attr('data-accept');
            var uploadFn = ice(this).attr('data-upload');
            var closeFn = ice(this).attr('data-del');
            var completeFn = ice(this).attr('data-complete');
            var uploadUrl = ice(this).attr('data-url');
            if(!ice('.iceUpload-list',this).length)this.innerHTML='<div class="iceUpload-list" style="display:none;"></div>'+this.innerHTML;
            var fileList = ice('.iceUpload-list',this)[0];
            var fileSrc=[];

            ice('.iceUpload-close',fileList).click(function(){
                var src = ice(this.parentNode).attr('data-url');
                ice.del(this.parentNode);
                fileSrc=[];
                ice('.iceUpload-item',fileList).each(function(){
                    fileSrc.push(ice(this).attr('data-url'));
                });
                closeFn && window[closeFn] && window[closeFn](src,fileSrc);
                completeFn && window[completeFn] && window[completeFn](src,fileSrc);
                //重新排序
                var order = ice('.iceUpload-order',fileList);
                order.each(function(s){
                    this.innerHTML = s+1;
                });
                if(!order.length)fileList.style.display='none';
            });

            //附件添加
            var fileBtn = ice('.btn',this)[0];
            if(fileBtn){
                fileBtn.onclick=function(){
                    if(!inputName) return iceui.pop('需设置name属性','warning');
                    if(!uploadUrl) return iceui.pop('需设置url上传地址属性','warning');
                    if(input)ice.del(input),input=null;
                    //创建input
                    var input = ice.c('input');
                    input.type='file';
                    input.multiple=true;
                    input.name = inputName;
                    if(inputAccept)input.accept = inputAccept;
                    input.onchange=function(){
                        ice.each(this.files, function () {
                            fileList.removeAttribute('style');
                            var item = ice.c('div');
                            item.className="iceUpload-item";
                            var order = ice.c('div');
                            order.className="iceUpload-order";
                            var info = ice.c('div');
                            info.className="iceUpload-info";
                            info.innerHTML='<span class="iceUpload-name">'+this.name+'</span><span class="iceUpload-size">'+ice.toSize(this.size)+'</span>';
                            var close = ice.c('div');
                            close.innerHTML='✕';
                            close.className='iceUpload-close';
                            var load = ice.c('div');
                            load.className="iceUpload-load";
                            load.innerHTML='<div class="loader-2"></div>';

                            //最终输出
                            item.appendChild(order);
                            item.appendChild(info);
                            item.appendChild(close);
                            item.appendChild(load);
                            fileList.appendChild(item);
                            //获取所有列表
                            fileItem = ice('.iceUpload-item',fileList);
                            //排序
                            order.innerHTML=fileItem.length;
                            close.onclick=function(){
                                var src = ice(item).attr('data-url');
                                ice.del(item);
                                fileSrc=[];
                                ice('.iceUpload-item',fileList).each(function(){
                                    fileSrc.push(ice(this).attr('data-url'));
                                });
                                closeFn && window[closeFn] && window[closeFn](src,fileSrc);
                                completeFn && window[completeFn] && window[completeFn](src,fileSrc);
                                //重新排序
                                var fileOrder=ice('.iceUpload-order',fileList);
                                if(fileOrder.length){
                                    for(var a=0,o;o=fileOrder[a++];){o.innerHTML=a;}
                                }else{
                                    fileList.style.display='none';
                                }
                            }
                            var formData = new FormData();
                            formData.append(input.name,this);
                            ice.ajax({
                                url: uploadUrl,
                                data: formData,
                                success: function (res) {
                                    if (!res.error) {
                                        ice(load).hide();
                                        ice(item).attr('data-url',res.url);
                                        fileList.removeAttribute('style');
                                        fileSrc = [];
                                        ice('.iceUpload-item',fileList).each(function(){
                                            fileSrc.push(ice(this).attr('data-url'));
                                        });
                                        uploadFn && window[uploadFn](res.url,fileSrc);
                                        completeFn && window[completeFn] && window[completeFn](res.url,fileSrc);
                                    }else{
                                        ice(item).addCss('iceUpload-error');
                                        ice('.iceUpload-name',item).html(res.error);
                                        ice(load).hide();
                                        alert(res.error);
                                    }
                                }
                            })
                        });
                    }
                    input.click();
                    return false;
                }
            }
        });
    }


    //多文件上传
    var fileBox = ice('.iceUpload-files');
    if(fileBox.length){
        fileBox.each(function(){
            if(!ice('.iceUpload-list',this).length)this.innerHTML='<div class="iceUpload-list"></div>'+this.innerHTML;
            this.innerHTML='<div class="iceUpload-control"></div>'+this.innerHTML;
            var fileList = ice('.iceUpload-list',this)[0];
            var fileInput = input = ice("input[type='file']",this)[0];
            var fileControl = ice('.iceUpload-control',this)[0];
            var fileListArr=new Array();
            if(!fileList.length)fileList.style.display='none';
            //附件添加
            var fileBtn = ice('.btn',this)[0];
            if(fileBtn){
                fileBtn.onclick=function(){
                    if(input)ice.del(input),input=null;
                    //创建input
                    var input = ice.c('input');
                    input.type=fileInput.type;
                    input.name=fileInput.name;
                    input.accept=fileInput.accept;
                    fileControl.appendChild(input);
                    input.onchange=function(){
                        //判断该文件是否已经添加
                        if(fileListArr.indexOf(input.value)==-1){
                            fileList.removeAttribute('style');
                            fileListArr.push(input.value);
                            var item = ice.c('div');
                            item.className="iceUpload-item";
                            var order = ice.c('div');
                            order.className="iceUpload-order";
                            var info = ice.c('div');
                            info.className="iceUpload-info";
                            info.innerHTML='<span class="iceUpload-name">'+this.files[0].name+'</span><span class="iceUpload-size">'+ice.toSize(this.files[0].size)+'</span>';
                            var close = ice.c('div');
                            close.innerHTML='✕';
                            close.className='iceUpload-close';

                            //最终输出
                            item.appendChild(order);
                            item.appendChild(info);
                            item.appendChild(close);
                            fileList.appendChild(item);
                            //获取所有文件列表
                            fileItem = ice('.iceUpload-item',fileList);
                            //文件排序
                            order.innerHTML=fileItem.length;
                            close.onclick=function(){
                                ice.del(item);
                                ice.del(input);
                                var index = fileListArr.indexOf(input.value);
                                if (index > -1)fileListArr.splice(index, 1);
                                //重新排序
                                var fileOrder=ice('.iceUpload-order',fileList);
                                if(fileOrder.length){
                                    for(var a=0,o;o=fileOrder[a++];){o.innerHTML=a;}
                                }else{
                                    fileList.style.display='none';
                                }
                            }
                        }else{
                            alert('该文件已经添加，不能重复添加！');
                            ice.del(input);
                        }
                    }
                    input.click();
                    return false;
                }
            }
        });
    }


    //轮播
    var slider = ice('.slider');
    if (slider) {
        slider.each(function () {
            var ani = ice.attr(this, 'data-slider-ani');
            var time = ice.attr(this, 'data-slider-time');
            var prevBtn = ice('.slider-prev', this);
            var nextBtn = ice('.slider-next', this);
            var buttonsBox = ice('.slider-buttons', this), buttons;
            var item = ice('.slider-item', this);
            var img = ice('img', item[0]);
            var num = item.length - 1;
            //如果没有轮播项的话，就不执行了
            if (!item.length) return;
            //默认激活第一个轮播项
            if (!item.hasCss('active')) item.s(0).addCss('active');
            //如果只有一个轮播项的话，也不用执行了，没JB啥意义！
            if (item.length == 1) return;
            if (img.length) {
                //如果轮播为图片的话，图片加载完后初始化
                var pic = new Image();
                pic.src = img[0].src;
                pic.onload = function () {
                    init();
                }
            } else {
                init();
            }
            //初始化
            function init() {
                time = time ? Number(time) : 3000;
                //遍历所有轮播项
                item.each(function (i) {
                    //设置轮播小圆点
                    if (buttonsBox.length) {
                        let html = i > 0 ? '<span></span>' : '<span class="active"></span>';
                        buttonsBox.append(html);
                    }
                    //移动端滑动
                    var startX = 0, moveX = 0;
                    this.addEventListener('touchstart', function (e) {
                        // 如果这个元素的位置内只有一个手指的话 
                        if (e.targetTouches.length == 1) {
                            startX = e.targetTouches[0].pageX;
                        }
                    }, false);
                    this.addEventListener('touchmove', function (e) {
                        // 如果这个元素的位置内只有一个手指的话 
                        if (e.targetTouches.length == 1) {
                            moveX = startX - e.targetTouches[0].pageX;
                        }
                    }, false);
                    this.addEventListener('touchend', function (e) {
                        if (moveX > 50) { //下一张
                            play();
                        } else if (moveX < -50) {
                            var s = !index ? num - 1 : (index === 1 ? num : index - 2);
                            play(s);
                        }
                        startX = 0;
                        moveX = 0;
                    }, false);
                });
                //轮播运行
                var run;
                function setPlay() {
                    run = setInterval(function () {
                        play();
                    }, time);
                }
                setPlay();

                //给小圆点添加事件
                if (buttonsBox.length) {
                    buttons = ice('span', buttonsBox);
                    buttons.click(function (a) {
                        if (this.className != 'active') {
                            play(a);
                        }
                    });
                    buttonsBox.on('mouseover', function () {
                        clearInterval(run)
                    });
                    buttonsBox.on('mouseout', function () {
                        setPlay();
                    });
                }

                //给按钮添加事件
                if (prevBtn.length) {
                    if (ice.isMobile()) {
                        prevBtn.on('touchend', function () {
                            var s = !index ? num - 1 : (index === 1 ? num : index - 2);
                            play(s);
                        });
                    } else {
                        prevBtn.on('mouseover', function () {
                            clearInterval(run)
                        });
                        prevBtn.on('mouseout', function () {
                            setPlay();
                        });
                        prevBtn.click(function () {
                            var s = !index ? num - 1 : (index === 1 ? num : index - 2);
                            play(s);
                        });
                    }
                }
                if (nextBtn.length) {
                    if (ice.isMobile()) {
                        prevBtn.on('touchend', function () {
                            play();
                        });
                    } else {
                        nextBtn.on('mouseover', function () {
                            clearInterval(run)
                        });
                        nextBtn.on('mouseout', function () {
                            setPlay();
                        });
                        nextBtn.click(function () {
                            play();
                        });
                    }
                }
            }
            //轮播
            var index = 1;   //轮播的当前索引
            var prev = 0;    //轮播的上一张索引
            var isClick = 0; //是否已点击
            var next = 1;    //播放动画是否为下一张
            //动画类型
            var key = {
                lr: { 0: 'left', 1: 'right' },
                ud: { 0: 'down', 1: 'up' },
                fade: { 0: 'fade', 1: 'fade' },
            }
            ani = ani ? ani : 'lr';
            ani = key[ani] ? ani : 'lr';
            var css = {
                prev: {
                    0: 'next slider-' + key[ani][1] + '-out',
                    1: 'active slider-' + key[ani][0] + '-in',
                    2: 'active next slider-' + key[ani][1] + '-out',
                    3: 'slider-' + key[ani][0] + '-in',
                },
                next: {
                    0: 'next slider-' + key[ani][0] + '-out',
                    1: 'active slider-' + key[ani][1] + '-in',
                    2: 'active next slider-' + key[ani][0] + '-out',
                    3: 'slider-' + key[ani][1] + '-in',
                }
            }
            function play(s) {
                //动画未执行完，防止重复点击
                if (isClick) return;
                isClick = 1;
                next = 1;
                index = s == undefined ? index : s;
                if (s != undefined) {
                    index = s;
                    if (index < prev) next = 0;
                }


                //动画方式
                var type = next ? 'next' : 'prev';
                //动画效果
                +function (a, b) {
                    ice.addCss(item[a], css[type][0]);
                    ice.addCss(item[b], css[type][1]);
                    setTimeout(function () {
                        ice.delCss(item[a], css[type][2]);
                        ice.delCss(item[b], css[type][3]);
                        prev = b;
                        isClick = 0;
                    }, 590);
                }(prev, index);
                //小圆点高亮
                if (buttonsBox.length) {
                    buttons.each(function (i) {
                        this.className = index == i ? 'active' : '';
                    });
                }
                index++;
                index = index > num ? 0 : index;
            }
        });
    }
});